package com.sina.shop.util;

import com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException;

/**
 * created  on 05/07/2017.
 */
public abstract class ExceptionUtils {


    private ExceptionUtils(){

    }

    public static Throwable getRootException(Throwable e){
        Throwable t ,t2 = e;
        t = t2;
        while (t2 != null){
            t = t2;
            t2 = t2.getCause();
        }
        return t;
    }

    public static String formatMsg(UnrecognizedPropertyException e){
        StringBuilder builder = new StringBuilder();
        builder.append("property '")
                .append(e.getPropertyName())
        .append("' is unrecognized field,known properties are [")
                ;
        for (Object o : e.getKnownPropertyIds()) {
            builder.append(o)
                    .append(",");
        }
        builder.deleteCharAt(builder.length() - 1)
        .append("]");
        return builder.toString();
    }

    public static String getSimpleMessage(Throwable e){
        Throwable root =  ExceptionUtils.getRootException(e);
        String msg;
        if(root instanceof UnrecognizedPropertyException){
            msg = formatMsg((UnrecognizedPropertyException)root);
        }else {
            msg = root.getMessage();
        }
        //InvalidFormatException
        return msg;
    }

}
